package org.domain.acount.session;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.domain.acount.entity.Papel;
import org.domain.acount.entity.Usuario;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator
{
    @Logger private Log log;
    @In EntityManager entityManager;
    @In Identity identity;
    @In Credentials credentials;
    
	@SuppressWarnings("unchecked")
	public boolean authenticate()
    {
    	Query query = entityManager.createNativeQuery("SELECT * FROM usuario WHERE username = ? AND senha = ?", Usuario.class);
    	query.setParameter(1, credentials.getUsername());
    	query.setParameter(2, credentials.getPassword());
    	Usuario usuario = (Usuario)query.getSingleResult();
    	if (usuario != null) {
    	 	List<Papel>  papeis = new ArrayList<Papel>();
    	   	query = entityManager.createNativeQuery("SELECT * FROM `papel` WHERE id_papel IN (SELECT papel_id_papel FROM usuario_has_papel WHERE usuario_username = ?)", Papel.class);
        	query.setParameter(1, usuario.getUsername());
    	   	papeis = query.getResultList();
    		if (papeis != null) {
    			for (Papel papel : papeis) {
    				identity.addRole(papel.getNome());
    			}
    		}
    		log.info("authenticating {0}", credentials.getUsername());    		
    		return true;
    	} else {
    		return false;
    	}
    }
    

}
